package com.ruoyi.chat.service.impl;

import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.response.ChatResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.io.IOException;

/**
 * @author WaKy
 * @version 1.0
 * 备份，暂不使用
 * 调用DeepSeek API的客户端
 */
@Service
public class DeepSeekClient {

    @Value("https://zhenze-huhehaote.cmecloud.cn/inference-api/exp-api/inf-1336844822260682752/v1/chat/completions")
    private String apiUrl;

    @Value("viKzmt21wnYaixRhuQHAGKMAlTfpvMmGINabEEWzJ7w")
    private String apiKey;

    @Value("default")
    private String model;
    private final WebClient webClient;

    public DeepSeekClient(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.baseUrl(apiUrl).build();
    }

    public SseEmitter generateText(ChatRequest request) {
        SseEmitter emitter = new SseEmitter();
        // 设置模型
        // 确保启用流式响应
        Flux<ChatResponse> responseFlux = webClient.post()
                .uri(apiUrl)
                .header("Authorization", "Bearer " + apiKey)
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(request)
                .retrieve()
                .bodyToFlux(ChatResponse.class)
                .doOnNext(response -> {
                    // 添加日志以调试返回的数据
                    System.out.println("Received response: " + response);
                });

        responseFlux.subscribe(
                response -> {
                    try {
                        emitter.send(response);  // 逐步发送响应到SSE
                    } catch (IOException e) {
                        emitter.completeWithError(e);  // 处理错误
                    }
                },
                emitter::completeWithError,  // 处理错误
                emitter::complete  // 完成SSE
        );

        //return ResponseEntity.ok(emitter);
        return null;
    }
}
